/********************************************************************************
 * Project Name		[JavaEE_JDBC]
 * File Name     	[JdbcTemplate.java]
 * Creation Date 	[2015-01-01]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ********************************************************************************/
package dao.impl3;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import pool.c3p0.JdbcUtils;

/**
 * JDBC 模板, 用于实现那一些通用的操作
 * 
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 * 
 */
public class JdbcTemplate {

	/**
	 * 数据库的相关操作
	 * 
	 * @param sql
	 * @param parameters
	 * @return
	 */
	private int databaseOperation(String sql, Object... parameters) {
		Connection connection = null;
		PreparedStatement statement = null;

		try {
			connection = JdbcUtils.getInstance().getConnection();
			statement = connection.prepareStatement(sql);
			for (int i = 0; i < parameters.length; i++) {
				statement.setObject(i + 1, parameters[i]);
			}
			return statement.executeUpdate();
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		} finally {
			JdbcUtils.getInstance().close(null, statement, connection);
		}
	}

	/**
	 * 插入记录
	 * 
	 * @param sql
	 * @param parameters
	 * @return
	 */
	public int save(String sql, Object... parameters) {
		return this.databaseOperation(sql, parameters);
	}

	/**
	 * 更新记录
	 * 
	 * @param sql
	 * @param parameters
	 * @return
	 */
	public int update(String sql, Object... parameters) {
		return this.databaseOperation(sql, parameters);
	}

	/**
	 * 删除记录
	 * 
	 * @param sql
	 * @param parameters
	 * @return
	 */
	public int delete(String sql, Object... parameters) {
		return this.databaseOperation(sql, parameters);
	}

	/**
	 * 查找对象
	 * 
	 * @param sql
	 * @param parameters
	 * @return
	 */
	public List<Object> find(String sql, ResultSetHandler handler, Object... parameters) {
		List<Object> resultObjects = new ArrayList<Object>();
		Connection connection = null;
		PreparedStatement statement = null;
		ResultSet resultSet = null;

		try {
			connection = JdbcUtils.getInstance().getConnection();
			statement = connection.prepareStatement(sql);
			for (int i = 0; i < parameters.length; i++) {
				statement.setObject(i + 1, parameters[i]);
			}
			resultSet = statement.executeQuery();
			while (resultSet.next()) {
				Object object = handler.handleResultSet(resultSet);
				resultObjects.add(object);
			}
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		} finally {
			JdbcUtils.getInstance().close(resultSet, statement, connection);
		}

		return resultObjects;
	}
}
